package com.xiaoma.client;

import com.xiaoma.entity.RpcRequest;
import com.xiaoma.entity.RpcResponse;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Author: xiaoma
 * @Date: 2021/7/5 13:51
 * @description: RPC客户端动态代理类
 */
public class RpcClientProxy implements InvocationHandler {

    private final RpcClient client;

    public RpcClientProxy(RpcClient client) {
        this.client = client;
    }

    @SuppressWarnings("unchecked")
    public <T> T getProxy(Class<T> clazz) {
        return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[]{clazz}, this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)  {
        RpcRequest rpcRequest = new RpcRequest(method.getDeclaringClass().getName(),
                method.getName(), args, method.getParameterTypes());
        //发送数据 获得返回值
        Object o = client.sendRequest(rpcRequest);
        if (o instanceof RpcResponse) {
            return ((RpcResponse) o).getData();
        } else {
            return o;
        }
    }
}
